package com.buildings.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.buildings.R;
import com.buildings.activity.table.LavaActivity;
import com.buildings.api.Api;
import com.buildings.base.BaseActivity;
import com.buildings.bean.AddressBean;
import com.buildings.bean.DivisionResultBean;
import com.buildings.bean.LoginBean;
import com.buildings.bean.TaskNewBean;
import com.buildings.http.BaseCallBack;
import com.buildings.http.JsonBuilder;
import com.buildings.http.MyHttpClient;
import com.buildings.util.CustomToast;
import com.buildings.util.DialogUtils;
import com.buildings.util.SPUtil;
import com.buildings.util.Utils;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.mapping.view.MapView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class TaskNewActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.et_task_name)
    EditText etTaskName;
    @BindView(R.id.et_task_number)
    TextView etTaskNumber;
    @BindView(R.id.et_project)
    TextView etProject;
    @BindView(R.id.et_task_detail)
    EditText etTaskDetail;

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_province)
    EditText etProvince;
    @BindView(R.id.et_city)
    EditText etCity;
    @BindView(R.id.et_area)
    EditText etArea;
    @BindView(R.id.btn_user)
    Button btnUser;
    public static final String PROVINCE = "province";
    public static final String CITY = "city";
    public static final String COUNTY = "county";

    private List<DivisionResultBean.Division> provinceList;
    private List<DivisionResultBean.Division> cityList;
    private List<DivisionResultBean.Division> countyList;

    private DivisionResultBean.Division province;
    private DivisionResultBean.Division city;
    private DivisionResultBean.Division county;

    private ArrayList<AddressBean> options1Items = new ArrayList<>(); //省
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();//市
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();//区

    private Dialog myDialog;
    //区级id
    private String divisionId;
    private String projectId;
    private String projectname;
    // 1 新建任务 2 修改任务
    private int type = 1;
    private String mapData = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_task);
        ButterKnife.bind(this);
        initView();
    }

    private TaskNewBean taskNewBean;

    private void initView() {
        if (!getIntent().hasExtra("projectId")) {
            finish();
        }
        if (!getIntent().hasExtra("projectname")) {
            finish();
        }
        projectId = getIntent().getStringExtra("projectId");
        projectname = getIntent().getStringExtra("projectname");
        type = getIntent().getIntExtra("type", 1);
        taskNewBean = (TaskNewBean) getIntent().getSerializableExtra("task");
        if (null != taskNewBean) {
            mapData = taskNewBean.getMapInfos();
            setDetail();
        }

        if (1 == type) {
            tvTitle.setText("新建任务");
            btnUser.setText("新建");
        } else {
            tvTitle.setText("修改任务");
            btnUser.setText("修改");
            etTaskNumber.setEnabled(false);
            etTaskName.setEnabled(false);
        }
        etProject.setText(projectname);
        getTaskNum(projectId);
    }

    private void setDetail() {
        etProvince.setText(taskNewBean.getCity());
        etCity.setText(taskNewBean.getCity());
        etArea.setText(taskNewBean.getArea());
        etTaskName.setText(taskNewBean.getTaskName());
        etTaskNumber.setText(taskNewBean.getTaskId());
        etTaskDetail.setText(taskNewBean.getRemark());
    }

    @OnClick({R.id.et_province, R.id.et_city, R.id.et_area, R.id.iv_back, R.id.btn_task_list, R.id.btn_user})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.et_province:
                Utils.hintKb(activity);
                if (myDialog == null) {
                    myDialog = DialogUtils.showRefreshDialog(activity);
                } else {
                    myDialog.show();
                }
                getDivisions("root", PROVINCE);
                break;
            case R.id.et_city:
                if (TextUtils.isEmpty(etProvince.getText().toString())) {
                    CustomToast.showToast(activity, "请先选择省");
                    return;
                }
                if (null != province
                        && "Municipality".equals(province.getDivisionType())) {
                    return;
                } else {
                    if (myDialog == null) {
                        myDialog = DialogUtils.showRefreshDialog(activity);
                    } else {
                        myDialog.show();
                    }
                    getDivisions(province.getDivisionId(), CITY);
                }
                break;
            case R.id.et_area:
                if (TextUtils.isEmpty(etCity.getText().toString())) {
                    CustomToast.showToast(activity, "请先选择市");
                    return;
                }
                if (myDialog == null) {
                    myDialog = DialogUtils.showRefreshDialog(activity);
                } else {
                    myDialog.show();
                }
                getDivisions(city.getDivisionId(), COUNTY);
                break;
            case R.id.btn_task_list:
                Intent intent = new Intent(this, MapActivity.class);
                intent.putExtra("MapInfos", mapData);
                startActivityForResult(intent, 1);
                break;
            case R.id.btn_user:
                if (1 == type) {
                    save();
                } else {
                    updata();
                }
                break;
        }
    }

    public void save() {
        String taskName = etTaskName.getText().toString().trim();
        String taskNumber = etTaskNumber.getText().toString().trim();
        String project = etProject.getText().toString().trim();
        String taskDetail = etTaskDetail.getText().toString().trim();
        String province = etProvince.getText().toString().trim();
        String city = etCity.getText().toString().trim();
        String area = etArea.getText().toString().trim();
        if (TextUtils.isEmpty(taskNumber)) {
            Toast("请录入任务编号");
            return;
        }
        if (TextUtils.isEmpty(taskName)) {
            Toast("请录入任务名称");
            return;
        }
        if (TextUtils.isEmpty(province)) {
            Toast("请录入地区");
            return;
        }

        if (TextUtils.isEmpty(city)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(area)) {
            Toast("请录入地区");
            return;
        }

        if (myDialog == null) {
            myDialog = DialogUtils.showRefreshDialog(activity);
        } else {
            myDialog.show();
        }
        JsonBuilder jsonBuilder = new JsonBuilder(this);
        jsonBuilder.put("taskName", taskName);
        jsonBuilder.put("city", city);
        jsonBuilder.put("province", province);
        jsonBuilder.put("area", area);
        jsonBuilder.put("taskId", taskNumber);
        jsonBuilder.put("belongProject", projectname);
        jsonBuilder.put("belongProjectID", projectId);
        jsonBuilder.put("createUser", SPUtil.get("userId", ""));
        jsonBuilder.put("remark", taskDetail);
        jsonBuilder.put("mapInfos", mapData);

        MyHttpClient
                .newBuilder()
                .post()
                .url(Api.SAVE_HDDC_TASK)
                .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack<LoginBean>() {
                    @Override
                    public void onSuccess(LoginBean bean) {
                        super.onSuccess(bean);
                        if (bean.getCode() == 200) {
                            CustomToast.showToast(TaskNewActivity.this, "提交成功");
                            finish();
                        }
                        if (myDialog != null)
                            myDialog.dismiss();
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(TaskNewActivity.this, "网络异常");
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(TaskNewActivity.this, "网络异常");
                    }
                });
    }

    public void updata() {
        if (null == taskNewBean) {
            return;
        }
        String taskName = etTaskName.getText().toString().trim();
        String taskNumber = etTaskNumber.getText().toString().trim();
        String project = etProject.getText().toString().trim();
        String taskDetail = etTaskDetail.getText().toString().trim();
        String province = etProvince.getText().toString().trim();
        String city = etCity.getText().toString().trim();
        String area = etArea.getText().toString().trim();
        if (TextUtils.isEmpty(taskNumber)) {
            Toast("请录入任务编号");
            return;
        }
        if (TextUtils.isEmpty(taskName)) {
            Toast("请录入任务名称");
            return;
        }
        if (TextUtils.isEmpty(province)) {
            Toast("请录入地区");
            return;
        }

        if (TextUtils.isEmpty(city)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(area)) {
            Toast("请录入地区");
            return;
        }
        if (myDialog == null) {
            myDialog = DialogUtils.showRefreshDialog(activity);
        } else {
            myDialog.show();
        }
        JsonBuilder jsonBuilder = new JsonBuilder(this);
        jsonBuilder.put("taskName", taskName);
        jsonBuilder.put("city", city);
        jsonBuilder.put("province", province);
        jsonBuilder.put("area", area);
        jsonBuilder.put("taskId", taskNumber);
        jsonBuilder.put("belongProject", projectname);
        jsonBuilder.put("belongProjectID", projectId);
        jsonBuilder.put("remark", taskDetail);
        jsonBuilder.put("mapInfos", mapData);
        jsonBuilder.put("updateUser", SPUtil.get("userId", ""));
        jsonBuilder.put("createUser", SPUtil.get("userId", ""));
        jsonBuilder.put("createTime", taskNewBean.getCreateTime());
        jsonBuilder.put("personIds", taskNewBean.getPersonIds());
        jsonBuilder.put("createUser", taskNewBean.getCreateUser());
        jsonBuilder.put("updateTime", taskNewBean.getUpdateTime());
        jsonBuilder.put("partionFlag", taskNewBean.getPartionFlag());
        jsonBuilder.put("id", taskNewBean.getId());
        jsonBuilder.put("objectCode", taskNewBean.getObjectCode());
        jsonBuilder.put("village", taskNewBean.getVillage());
        jsonBuilder.put("town", taskNewBean.getTown());
        jsonBuilder.put("isValid", taskNewBean.getIsValid());

        MyHttpClient
                .newBuilder()
                .put()
                .url(Api.SAVE_HDDC_TASK)
                .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack<LoginBean>() {
                    @Override
                    public void onSuccess(LoginBean bean) {
                        super.onSuccess(bean);
                        if (bean.getCode() == 200) {
                            CustomToast.showToast(TaskNewActivity.this, "提交成功");
                            finish();
                        }
                        if (myDialog != null)
                            myDialog.dismiss();
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(TaskNewActivity.this, "网络异常");
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(TaskNewActivity.this, "网络异常");
                    }
                });
    }


    private void getDivisions(String divisionid, final String type) {
        String url = Api.GET_LOCATION + "divisions/" + divisionid + "/subdivisions";
        MyHttpClient
                .newBuilder()
                .get()
                .url(url)
                .build()
                .enqueue(new BaseCallBack<DivisionResultBean>() {
                    @Override
                    public void onSuccess(DivisionResultBean divisionResultBean) {
                        super.onSuccess(divisionResultBean);
                        if (myDialog != null)
                            myDialog.dismiss();
                        if (divisionResultBean != null && divisionResultBean.getCode() == 200) {
                            if (divisionResultBean.getData() != null) {
                                if (TextUtils.equals(PROVINCE, type)) {
                                    provinceList = divisionResultBean.getData();
                                    showPickerView(provinceList, PROVINCE);
                                } else if (TextUtils.equals(CITY, type)) {
                                    cityList = divisionResultBean.getData();
                                    showPickerView(cityList, CITY);
                                } else if (TextUtils.equals(COUNTY, type)) {
                                    countyList = divisionResultBean.getData();
                                    showPickerView(countyList, COUNTY);
                                }

                            }
                        }
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        CustomToast.showToast(activity, "网络异常");

                        if (myDialog != null)
                            myDialog.dismiss();
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        CustomToast.showToast(activity, "网络异常");

                        if (myDialog != null)
                            myDialog.dismiss();
                    }
                });

    }

    private void showPickerView(final List<DivisionResultBean.Division> list, final String type) {// 弹出选择器（省市区三级联动）
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                DivisionResultBean.Division division = list.get(options1);
                switch (type) {
                    case PROVINCE:
                        province = division;
                        if (null != province
                                && "Municipality".equals(province.getDivisionType())) {
                            city = division;
                            etCity.setText(division.getDivisionName());
                        } else {
                            city = null;
                            etCity.setText("");
                        }
                        county = null;
                        etArea.setText("");
                        etProvince.setText(division.getDivisionName());
                        break;
                    case CITY:
                        city = division;
                        county = null;
                        etArea.setText("");
                        etCity.setText(division.getDivisionName());
                        divisionId = division.getDivisionId();
                        break;
                    case COUNTY:
                        county = division;
                        etArea.setText(division.getDivisionName());
                        divisionId = division.getDivisionId();
                        break;
                }
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(list);//一级选择器
        pvOptions.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 3) {
            String result = data.getStringExtra("result");
            mapData = result;
        }
    }

    private void getTaskNum(String projectId) {
        String url = Api.GET_TASK_CODE + "/" + projectId;
        MyHttpClient
                .newBuilder()
                .get()
                .url(url)
                .build()
                .enqueue(new BaseCallBack<String>() {
                    @Override
                    public void onSuccess(String divisionResultBean) {
                        super.onSuccess(divisionResultBean);
                        if (myDialog != null)
                            myDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(divisionResultBean);
                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                String imageUrl = jsonObject.getString("data");
                                etTaskNumber.setText(TextUtils.isEmpty(imageUrl) ? "" : imageUrl);
                            } else {
                                CustomToast.showToast(activity, "任务编号获取失败");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            CustomToast.showToast(activity, "任务编号获取失败");
                        }
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        CustomToast.showToast(activity, "网络异常");
                        if (myDialog != null)
                            myDialog.dismiss();
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        CustomToast.showToast(activity, "网络异常");
                        if (myDialog != null)
                            myDialog.dismiss();
                    }
                });

    }
}
